﻿using huqiang.Communication;
using huqiang.DataSet;
using huqiang.ProtoDataPro;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class NetUser : KcpUser
{
    /// <summary>
    /// 用户标签
    /// </summary>
    public string Tag;
    public sealed override void HandleMsg(ref UserMsg msg, string str, byte[] dat)
    {
        if (msg.Error > 0)
        {
            DataProc.HandleError(this, msg.DataType, msg.CmdType, msg.Error, str);
        }
        else
        {
            switch (msg.DataType)
            {
                case EnvelopeType.Json:
                    break;
                case EnvelopeType.String:
                    huqiang.StringDataPro.StringDataHandle.HandleMsg(this, msg.CmdType, msg.Cmd, str);
                    break;
                case EnvelopeType.ProtoBuf:
                    huqiang.ProtoDataPro.ProtobufHandle.HandleMsg(this, msg.CmdType, msg.Cmd, dat);
                    break;
                default:
                    DataProc.HandleMsg(this, msg.DataType, msg.CmdType, msg.Cmd, dat);
                    break;
            }
        }
    }
    public override void Connect()
    {
        if (Tag == null)
        {
            Tag = endPoint.Address.ToString();
        }
    }
    public RecordFile record;
    public void OpenOrCreateLog()
    {
        if (record != null)
            return;
        var now = DateTime.Now;
        string filename = now.Year + "-" + now.Month + "-" + now.Day;
        string dic = "Record";
        if (!Directory.Exists(dic))
            Directory.CreateDirectory(dic);
        dic = dic + "/" + filename;
        if (!Directory.Exists(dic))
            Directory.CreateDirectory(dic);
        string name = endPoint.Address.ToString() + "-" + port + ".ini";
        record = RecordFile.Open(filename, name);
        string sec = "[" + now.Hour + "-" + now.Minute + "-" + now.Second + "]\n";
        record.Write(sec);
    }
    public override bool Disconnect()
    {
        if(record!=null)
        {
            record.Dispose();
            record = null;
        }
        return base.Disconnect();
    }
    public Log log;
    public void ResetLog(string tag)
    {
        Tag = tag;
        var chars = System.IO.Path.GetInvalidPathChars();
        if (tag.IndexOfAny(chars) >= 0)
        {
            tag = endPoint.Address.ToString();
        }
        log = new Log(tag);
    }
}
